import requests
import time
from base.RedisHandler import RedisHandler


class CheckIpHandler:
    def __init__(self):
        self.redis = RedisHandler()
        self.baidu_url = "https://www.baidu.com/"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
        }

    def check(self):
        # 检测redis里的代理是否有效，无效的就剔除
        for ip in self.redis.get_all_ip():
            port = self.redis.get_port(ip)
            proxies = {
                "http": "http://%s:%s" % (ip, port)
            }
            status = requests.get(self.baidu_url, proxies=proxies).status_code
            if status == 200:
                print(f"当前代理 {ip}: {port} 有效。")
            else:
                self.redis.remove_ip(ip)
                print(f"当前代理 {ip}: {port} 无效，已剔除！")
            time.sleep(0.3)


if __name__ == '__main__':
    obj = CheckIpHandler()
    obj.check()
